package com.itheima.aspect;

import com.itheima.domain.SysLog;
import com.itheima.service.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class Aspect2 {
    @Autowired
    private SysLogService sysLogService;

    @Pointcut("execution(* com.itheima.service.EquipmentService.add*(..))")
    private void pt() {
    }

    @Around("pt()")
    public Object addLog(ProceedingJoinPoint pjp) throws Throwable {

        Object obj = pjp.proceed(pjp.getArgs());
        Class<?> clazz =pjp.getTarget().getClass();
        MethodSignature sign = (MethodSignature) pjp.getSignature();
       /*
       //该行代码获取不到被自定义注解的方法，method指向void com.itheima.service.EquipmentService.addEquipment(Equipment)
       //并非需要的public void com.itheima.service.impl.EquipmentServiceImpl.addEquipment(com.itheima.domain.Equipment)
       Method method2=sign.getMethod();
       */
        Method method = clazz.getDeclaredMethod(sign.getName(), sign.getParameterTypes());
        RequiredLog requiredLog = method.getAnnotation(RequiredLog.class);

        if(requiredLog!=null){
            SysLog sysLog = new SysLog();
            String operation = requiredLog.operation();
            sysLog.setOperation(operation);
            //获取请求参数
            String params = Arrays.toString(pjp.getArgs());
            //sysLog.setMethod(sign.getName());只获得addEquipment
            sysLog.setMethod(clazz.getName()+"."+method.getName());
            sysLog.setParams(params);
            sysLog.setUsername("admin");
            sysLog.setCreated(new Date());
            sysLogService.addSysLog(sysLog);
        }
        return obj;
    }
}